package com.demarc.pesquisas.web.converter;

import java.text.DecimalFormat;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.faces.convert.NumberConverter;

import org.apache.commons.lang3.StringUtils;

import com.demarc.pesquisas.infraestrutura.mensagem.MensagemJsfUtils;
import com.demarc.pesquisas.infraestrutura.web.jsf.JsfUtil;
import com.demarc.pesquisas.negocio.util.NumberUtils;

@FacesConverter(forClass = Double.class)
public class DoubleConverter extends NumberConverter {

	private static final String DOUBLE_MESSAGE_ID = "com.demarc.pesquisas.web.converter.DoubleConverter.DOUBLE";

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object input) {
		String value = null;

		if (input instanceof Double) {
			DecimalFormat formatter = (DecimalFormat) DecimalFormat
					.getInstance(context.getViewRoot().getLocale());
			formatter.applyPattern(NumberUtils.getStringPattern(getScale()));
			value = formatter.format(input);
		}

		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String input) {

		try {
			Double valor = null;

			if (StringUtils.isNotBlank(input)) {
				DecimalFormat formatter = (DecimalFormat) DecimalFormat
						.getInstance(context.getViewRoot().getLocale());
				formatter
						.applyPattern(NumberUtils.getStringPattern(getScale()));

				Number number = formatter.parse(input.trim().replace(
						',',
						formatter.getDecimalFormatSymbols()
								.getDecimalSeparator()));
				valor = Double.valueOf(number.doubleValue());
			}
			return valor;
		} catch (java.text.ParseException e) {
			FacesMessage facesMessage = MensagemJsfUtils.criarFacesMessage(
					FacesMessage.SEVERITY_ERROR, DOUBLE_MESSAGE_ID,
					JsfUtil.getLabel(context, component));
			throw new ConverterException(facesMessage, e);
		}
	}

	protected int getScale() {
		return 2;
	}
}